<template>
  <load-more ref="listRef" :enable-refresh="false" @load="handleLoad">
    <space-post-item v-for="item in posts" :key="item.key" :post="item"></space-post-item>
  </load-more>
</template>

<script>
import { reactive, toRefs, watch, computed } from 'vue'
import LoadMore from '@/components/LoadMore'
import SpacePostItem from './postItem'
export default {
  name: 'SpacePosts',
  components: {
    LoadMore,
    SpacePostItem
  },
  emits: ['onLoad'],
  props: {
    list: {
      type: Array
    }
  },
  setup(props, { emit }) {
    const params = reactive({
      listRef: null,      
      posts: computed(() => {
        const formatPost = []
        if (!props.list) {
          return formatPost
        }
        for (const item of props.list) {
            const { card, desc, desc: { type }, display, extension } = item
            const cardJson = JSON.parse(card)
            item.cardJson = cardJson
            let [topics, emojis, votes] = [null, null, null]
            if (typeof display.topic_info !== 'undefined') {
                topics = display.topic_info.topic_details
            }
            if (typeof display.emoji_info !== 'undefined') {
                emojis = display.emoji_info.emoji_details
            }
            if (typeof extension !== 'undefined') {
                if (typeof extension.vote_cfg !== 'undefined') {
                    votes = extension.vote_cfg
                }
            }
            const params = {
                cardJson,
                originJson: null,
                desc,
                display
            }
            let tempPost = null
            // 获取自己所发的 具体动态
            tempPost = dispatch(type, params)

            if (type === 1) {
                // 回复他人的动态
                if (typeof cardJson.origin === 'undefined') {
                    // 原动态 被删除失效了
                    tempPost.miss = 1
                } else {
                    let [tempOriginPost, originTopics, originEmojis] = [null, null, null]
                    const originJson = JSON.parse(cardJson.origin)
                    const originType = desc.orig_type
                    item.cardJson.originJson = originJson
                    params.originJson = originJson
                    // console.log('originType' + originType)
                    if (typeof display.origin !== 'undefined') {
                        if (typeof display.origin.topic_info !== 'undefined') {
                            originTopics = display.origin.topic_info.topic_details
                        }
                        if (typeof display.origin.emoji_info !== 'undefined') {
                            originEmojis = display.origin.emoji_info.emoji_details
                        }
                    }
                    // 获取回复他人的 具体动态
                    tempOriginPost = dispatch(originType, params)

                    let tempAppend = {
                        key: `o${desc.orig_dy_id_str}`,
                        id: desc.orig_dy_id_str,
                        level: 2,
                        type: originType,
                        isFollowed: 0,
                        topics: originTopics,
                        emojis: originEmojis
                    }
                    if (!tempOriginPost) {
                        tempAppend = createPost(tempAppend)
                    }
                    tempPost.origins[0] = Object.assign({}, tempOriginPost || {}, tempAppend)
                }
            }
            let append = {
                key: desc.dynamic_id_str,
                id: desc.dynamic_id_str,
                level: 1,
                type,
                isFollowed: item.display.relation.is_followed,
                // 是否置顶
                isSpaceTop: item.extra ? item.extra.is_space_top === 1 : false,
                official: desc.user_profile.card.official_verify,
                topics,
                emojis,
                votes
            }
            if (!tempPost) {
                append = createPost(append)
            }
            tempPost = Object.assign({}, tempPost || {}, append)
            formatPost.push(tempPost)
        }
        return formatPost
      })
    })

    const createPost = ({
        key,
        id,
        level,
        type,
        mid,
        userName,
        avatar,
        vipStatus,
        official,
        postTime,
        like,
        repost,
        reply,
        isFollowed = 0,
        msg = null,
        topics = null,
        emojis = null,
        ats = null,
        votes = null,
        miss = 0,
        origins = null,
        pictures = null,
        music = null,
        video = null,
        bangumi = null,
        article = null,
        daka = null,
        live = null,
        shortVideo = null
      } = {}) => {
        return {
          key,
          id,
          level,
          type,
          mid,
          userName,
          avatar,
          vipStatus,
          official,
          postTime,
          like,
          repost,
          reply,
          isFollowed,
          msg,
          topics,
          emojis,
          ats,
          votes,
          miss,
          origins,
          pictures,
          music,
          video,
          bangumi,
          article,
          daka,
          live,
          shortVideo
        }
    }

    // 分发类型对应的解析函数
    const dispatch = (type, params) => {
        let post = null
        switch (type) {
            case 1:
                // 回复他人发的动态
                post = genReply(params)
                break
            case 2:
                // 文本带图文动态
                post = genPictureText(params)
                break
            case 4:
                // 纯文本动态
                post = genPureText(params)
                break
            case 8:
                // 视频动态
                post = genVideo(params)
                break
            case 16:
                // 短视频动态
                post = genShortVideo(params)
                break
            case 64:
                // 长的文章动态
                post = genArticle(params)
                break
            case 256:
                // 音乐动态
                post = genMusic(params)
                break
            case 512:
            case 4099:
            case 4101:
                // 动态是 动画|番剧|记录片|
                post = genBangumi(params)
                break
            case 2048:
                // 打卡动态
                post = genDaka(params)
                break
            case 4200:
                // 直播 录播
                post = genLive(params)
                break
            default:
                post = genReply(params)
        }
        return post
    }

    // type: 1 生成回复他人的动态
    const genReply = ({
        cardJson,
        originJson = null,
        desc,
        display
    } = {}) => {      
        const item = cardJson.item
        const reply = createPost({
          mid: cardJson.user.uid,
          userName: cardJson.user.uname,
          avatar: cardJson.user.face,
          vipStatus: desc.user_profile.vip.vipStatus,
          like: desc.like,
          repost: desc.repost,
          reply: desc.comment,
          msg: item.content,
          postTime: item.timestamp || desc.timestamp,
          ats: item.ctrl ? (JSON.parse(item.ctrl)) : null,
          origins: []
        })
        return reply
    }
    // type:2 生成图文动态
    const genPictureText = ({
        cardJson,
        originJson = null,
        desc,
        display
    } = {}) => {
        let picText = null
        if (originJson) {
          const oitem = originJson.item
          const ouser = cardJson.origin_user
          picText = createPost({
            mid: ouser.info.uid,
            userName: ouser.info.uname,
            avatar: ouser.info.face,
            vipStatus: ouser.vip.vipStatus,
            like: desc.origin.like,
            repost: desc.origin.repost,
            reply: oitem.reply,
            msg: oitem.description,
            postTime: oitem.upload_time,
            pictures: oitem.pictures,
            ats: oitem.at_control ? (JSON.parse(oitem.at_control)) : null
          })
        } else {
          const tempItem = cardJson.item
          const tempUser = cardJson.user
          picText = createPost({
            mid: tempUser.uid,
            userName: tempUser.name,
            avatar: tempUser.head_url,
            vipStatus: tempUser.vip.vipStatus,
            postTime: tempItem.upload_time,
            msg: tempItem.description,
            pictures: tempItem.pictures,
            like: desc.like,
            repost: desc.repost,
            reply: tempItem.reply,
            ats: tempItem.at_control ? (JSON.parse(tempItem.at_control)) : null
          })
        }
        return picText
    }
    // type:4 生成纯文本动态
    const genPureText = ({
        cardJson,
        originJson = null,
        desc,
        display
    } = {}) => {
        let pureText = null
        if (originJson) {
          const oitem = originJson.item
          const ouser = cardJson.origin_user
          pureText = createPost({
            mid: ouser.info.uid,
            userName: ouser.info.uname,
            avatar: ouser.info.face,
            vipStatus: ouser.vip.vipStatus,
            like: desc.origin.like,
            repost: desc.origin.repost,
            reply: oitem.reply,
            msg: oitem.content,
            postTime: oitem.timestamp,
            ats: oitem.ctrl ? (JSON.parse(oitem.ctrl)) : null          
          })
        } else {
          const tempItem = cardJson.item
          const tempUser = cardJson.user
          pureText = createPost({
            mid: tempUser.uid,
            userName: tempUser.uname,
            avatar: tempUser.face,
            vipStatus: desc.user_profile.vip.vipStatus,
            postTime: tempItem.timestamp,
            msg: tempItem.content,
            like: desc.like,
            repost: desc.repost,
            reply: tempItem.reply,
            ats: tempItem.ctrl ? (JSON.parse(tempItem.ctrl)) : null
          })
        }
        return pureText
    }
    // type:8 生成视频动态
    const genVideo = ({
        cardJson,
        originJson = null,
        desc,
        display
    } = {}) => {
        let video = null
        if (originJson) {
          const ouser = cardJson.origin_user
          video = createPost({
            mid: ouser.info.uid,
            userName: ouser.info.uname,
            avatar: ouser.info.face,
            vipStatus: ouser.vip.vipStatus,
            like: originJson.stat.like,
            repost: desc.origin.repost,
            reply: originJson.stat.reply,
            msg: originJson.dynamic,
            postTime: originJson.pubdate,
            video: {
              aid: originJson.aid,
              bvid: desc.origin.bvid,
              cid: originJson.cid,
              title: originJson.title,
              msg: originJson.dynamic,
              pic: originJson.pic,
              duration: originJson.duration,
              view: originJson.stat.view,
              danmaku: originJson.stat.danmaku,
              postTime: originJson.pubdate
            }
          })
        } else {
          video = createPost({
            mid: cardJson.owner.mid,
            userName: cardJson.owner.name,
            avatar: cardJson.owner.face,
            vipStatus: desc.user_profile.vip.vipStatus,
            like: cardJson.stat.like,
            repost: desc.repost,
            reply: cardJson.stat.reply,
            msg: cardJson.dynamic,
            postTime: cardJson.pubdate,
            video: {
              aid: cardJson.aid,
              bvid: desc.bvid,
              cid: cardJson.cid,
              msg: cardJson.dynamic,
              title: cardJson.title,
              pic: cardJson.pic,
              duration: cardJson.duration,
              view: cardJson.stat.view,
              danmaku: cardJson.stat.danmaku,
              postTime: cardJson.pubdate
            }
          })
        }
        return video
    }
    // type:16 生成短视频动态
    const genShortVideo = ({
        cardJson,
        originJson = null,
        desc,
        display
    } = {}) => {
        let shortVideo = null
        if (originJson) {
          const oitem = originJson.item
          const ouser = cardJson.origin_user
          shortVideo = createPost({
            mid: ouser.info.uid,
            userName: ouser.info.uname,
            avatar: ouser.info.face,
            vipStatus: ouser.vip.vipStatus,
            postTime: oitem.timestamp,
            msg: oitem.description,
            like: desc.origin.like,
            repost: desc.origin.repost,
            reply: oitem.reply,
            shortVideo: {
              view: oitem.watched_num,
              duration: oitem.video_time,
              videoUrl: oitem.video_playurl,
              poster: oitem.cover.default
            }
          })
        } else {
          const tempItem = cardJson.item
          const user = desc.user_profile
          shortVideo = createPost({
            mid: user.info.uid,
            userName: user.info.uname,
            avatar: user.info.face,
            vipStatus: user.vip.vipStatus,
            like: desc.like,
            repost: desc.repost,
            reply: tempItem.reply,
            msg: tempItem.description,
            postTime: desc.timestamp,
            shortVideo: {
              view: tempItem.watched_num,
              duration: tempItem.video_time,
              videoUrl: tempItem.video_playurl,
              poster: tempItem.cover.default
            }
          })
        }
        return shortVideo
    }
    // type:64 生成长文
    const genArticle = ({
        cardJson,
        originJson = null,
        desc,
        display
    } = {}) => {
        let article = null
        if (originJson) {
          const author = originJson.author
          article = createPost({
            mid: author.mid,
            userName: author.name,
            avatar: author.face,
            vipStatus: author.vip.status,
            like: originJson.stats.like,
            repost: desc.repost,
            reply: originJson.stats.reply,
            msg: '',
            postTime: originJson.ctime,
            article: {
              id: originJson.id,
              title: originJson.title,
              summary: originJson.summary,
              view: originJson.stats.view,
              pictures: originJson.image_urls
            }
          })
        } else {
          const profile = desc.user_profile
          article = createPost({
            mid: profile.uid,
            userName: profile.info.uname,
            avatar: profile.info.face,
            vipStatus: profile.vip.vipStatus,
            like: cardJson.stats.like,
            repost: desc.repost,
            reply: cardJson.stats.reply,
            postTime: cardJson.ctime,
            msg: '',
            article: {
              id: cardJson.id,
              title: cardJson.title,
              summary: cardJson.summary,
              view: cardJson.stats.view,
              pictures: cardJson.image_urls
            }
          })
        }
        return article
    }
    // type: 256 生成音乐动态
    const genMusic = ({
        cardJson,
        originJson = null,
        desc,
        display
    } = {}) => {
        let music = null
        let user = null
        if (originJson) {
          user = cardJson.origin_user
          music = createPost({
            mid: user.info.uid,
            userName: user.info.uname,
            avatar: user.info.face,
            vipStatus: user.vip.vipStatus,
            like: desc.origin.like,
            repost: desc.origin.repost,
            reply: originJson.replyCnt,
            msg: originJson.intro,
            postTime: desc.origin.timestamp,
            music: {
              id: originJson.id,
              title: originJson.title,
              cover: originJson.cover,
              view: originJson.playCnt
            }
          })
        } else {
          user = desc.user_profile
          music = createPost({
            mid: user.info.uid,
            userName: user.info.uname,
            avatar: user.info.face,
            vipStatus: user.vip.vipStatus,
            like: desc.like,
            repost: desc.repost,
            reply: cardJson.replyCnt,
            msg: cardJson.intro,
            postTime: desc.timestamp,
            music: {
              id: cardJson.id,
              title: cardJson.title,
              view: cardJson.playCnt,
              cover: cardJson.cover
            }
          })
        }
        return music
    }
    // type: 2048 生成打卡动态
    const genDaka = ({
        cardJson,
        originJson = null,
        desc,
        display
    } = {}) => {
        let daka = null
        const user = desc.user_profile
        let sketch = null
        if (originJson) {
          const ouser = cardJson.origin_user
          sketch = originJson.sketch
          daka = createPost({
            mid: ouser.uid,
            userName: ouser.uname,
            avatar: ouser.face,
            vipStatus: ouser.vip.vipStatus,
            like: desc.origin.like,
            repost: desc.origin.repost,
            reply: 0,
            msg: originJson.vest.content,
            postTime: desc.origin.timestamp,
            daka: {
              id: sketch.sketch_id,
              title: sketch.title,
              desc: sketch.desc_text,
              cover: sketch.cover_url
            }
          })
        } else {
          const cuser = cardJson.user
          sketch = cardJson.sketch
          daka = createPost({
            mid: cuser.uid,
            userName: cuser.uname,
            avatar: cuser.face,
            vipStatus: user.vip.vipStatus,
            like: desc.like,
            repost: desc.repost,
            reply: desc.comment,
            postTime: desc.timestamp,
            msg: cardJson.vest.content,
            daka: {
              id: sketch.sketch_id,
              title: sketch.title,
              desc: sketch.desc_text,
              cover: sketch.cover_url
            }
          })
        }
        return daka
    }
    // type: 512|4099|4101 生成 动画|番剧|记录片动态
    const genBangumi = ({
        cardJson,
        originJson = null,
        desc,
        display
    } = {}) => {
        let bangumi = null
        if (originJson) {
          bangumi = createPost({
            mid: originJson.episode_id,
            userName: originJson.apiSeasonInfo.title,
            avatar: '',
            vipStatus: 0,
            like: desc.origin.like,
            repost: desc.origin.repost,
            reply: originJson.reply_count,
            postTime: originJson.apiSeasonInfo.ts,
            bangumi: {
              aid: originJson.aid,
              episodeId: originJson.episode_id,
              title: originJson.new_desc ? (originJson.new_desc) : (`${originJson.index} ${originJson.index_title}`),
              view: originJson.play_count,
              danmaku: originJson.bullet_count,
              pic: originJson.cover
            }
          })
        }
        return bangumi
    }
    // type:4200 生成直播动态
    const genLive = ({
        cardJson,
        originJson = null,
        desc,
        display
    } = {}) => {
        let live = null
        let user = null
        if (originJson) {
          user = cardJson.origin_user
          live = createPost({
            mid: user.info.uid,
            userName: user.info.uname,
            avatar: user.info.face,
            vipStatus: user.vip.vipStatus,
            postTime: desc.origin.timestamp,
            live: {
              roomid: originJson.roomid,
              roomTypeId: originJson.area_v2_id,
              roomType: originJson.area_v2_name,
              liveStatus: originJson.live_status,
              liveTime: originJson.live_time,
              title: originJson.title,
              cover: originJson.cover,
              online: originJson.online
            }
          })
        }
        return live
    }

    const stopLoading = () => {
      params.listRef && params.listRef.stopLoad()
    }

    const complete = () => {
      params.listRef && params.listRef.completeLoad()
    }

    const handleLoad = () => {   
      emit('onLoad')
    }

    return {
      ...toRefs(params),
      handleLoad,
      stopLoading,
      complete
    }
  }
}
</script>

<style>

</style>